package models

import (
	"errors"
	//	"log"
	"strconv"
	"time"

	"git.oschina.net/54json/gomysql"

	"fmt"

	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type Category struct {
	Id      int64
	Title   string
	Created time.Time `orm:"index"`
	Views   int64     `orm:"index"`
}

type Topic struct {
	Id              int64
	Uid             int64
	Title           string
	Content         string `orm:"size(5000)"`
	Attachment      string
	Created         time.Time `orm:"index"`
	Updated         time.Time `orm:"index"`
	Views           int64     `orm:"index"`
	Author          string
	ReplyTime       time.Time `orm:"index"`
	ReplyCount      int64
	ReplyLastUserId int64
}
type News struct {
	Id                int64
	Title             string
	Des               string
	Time              string
	Origin            string
	Origin_detail_url string
	Content           string
}

func GetAllGoods() (map[int]map[string]string, error) {
	m, err := gomysql.SetDB("default")
	rows := m.SetTable("ecs_goods").FindAll()
	fmt.Println(rows)
	return rows, err
}
func GetAllCats() (map[int]map[string]string, error) {
	m, err := gomysql.SetDB("default")
	rows := m.SetTable("ecs_category").FindAll()
	fmt.Println(rows)
	return rows, err
}
func GetGoodsDetail(id string) map[string]string {
	m, _ := gomysql.SetDB("default")
	row := m.SetTable("ecs_goods").Where("goods_id=" + id).FindOne()
	return row[1]
}
func AddTopic(title, content string) error {
	o := orm.NewOrm()
	if len(title) == 0 || len(content) == 0 {
		return errors.New("参数有误")
	}
	topic := Topic{Title: title, Content: content}
	_, err := o.Insert(&topic)
	return err
}
func GetAllTopics() ([]*Topic, error) {
	o := orm.NewOrm()
	topics := make([]*Topic, 0)
	QS := o.QueryTable("topic")
	_, err := QS.All(&topics)
	return topics, err
}
func RegisterDB() {
	orm.RegisterModel(new(Category), new(Topic))
	//orm.RegisterDriver()
}

func AddCategory(title string) error {
	o := orm.NewOrm()
	cat := Category{Title: title}
	err := o.Read(&cat)

	if err != orm.ErrNoRows {
		return err
	}
	_, err = o.Insert(&cat)
	return err
	//	o := orm.NewOrm()
	//	cate := &Category{Title: title}
	//	qs := o.QueryTable("category")
	//	err := qs.Filter("title", title).One(cate)
	//	if err == nil {
	//		return err
	//	}
	//	_, err = o.Insert(cate)
	//	if err != nil {
	//		return err
	//	}
	//	return nil
}
func GetAllCategory() ([]*Category, error) {
	o := orm.NewOrm()
	cates := make([]*Category, 0)
	QS := o.QueryTable("category")
	_, err := QS.All(&cates)
	return cates, err
}

func DelCategory(id string) error {
	cid, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		return err
	}
	o := orm.NewOrm()
	cate := &Category{Id: cid}
	_, err = o.Delete(cate)
	return err
}
